package com.d2.modules.system.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.d2.common.annotation.Dict;
import com.d2.common.util.SpringContextUtils;
import com.d2.modules.system.dict.service.DictService;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class DaoUtils {
    public static <T> Page<T> convertListToPage(Page<T> page, List<T> list){
        page.setTotal(list.size());
        long current = page.getCurrent();
        long size = page.getSize();
        int fromIndex = Math.toIntExact((current - 1) * size);
        if(fromIndex>=list.size()){
            fromIndex = list.size()-1;
        }
        if(fromIndex<0){
            fromIndex = 0;
        }
        int toIndex = Math.toIntExact(current * size);
        if(toIndex > list.size()){
            toIndex = list.size();
        }
        List<T> rd = list.subList(fromIndex, toIndex);
        page.setRecords(rd);
        return page;
    }

    public static String translate(Dict dict, Object value){
        if(value == null){
            return null;
        }
        String textColumn = dict.keyColumn();
        String table = dict.table();
        String keyColumn = dict.keyColumn();
        if(!Objects.equals(textColumn, "")
                && !Objects.equals(table, "")
                && !Objects.equals(keyColumn, "")) {
            SQLManager sqlManager = SpringContextUtils.getBean(SQLManager.class);
            List<Map> execute = sqlManager.execute(new SQLReady(
                            String.format("select %s from %s where %s=?", textColumn, table, keyColumn), value.toString()),
                    Map.class);
            if (!execute.isEmpty()) {
                Map map1 = execute.get(0);
                Object o1 = map1.get(textColumn);
                if (o1 != null) {
                    return o1.toString();
                }
            }
        }else {
            String s = dict.dictCode();
            if("".equals(s)){
                DictService dictService = SpringContextUtils.getBean(DictService.class);
                return dictService.translate(s, value);
            }
        }
        return null;
    }
}
